<?php
	// check parameters
	if (sizeof($_GET) != 3)
	{
		echo "Usage: Invalid number of parameters!";
		exit();
	}

	// if passed then check whether $_GET contains correct parameter names
	if (!array_key_exists('code', $_GET) || !array_key_exists('hdi', $_GET) || !array_key_exists('appkey', $_GET))
	{
		echo "Usage: Please include parameters 'code', 'hid', and 'appkey'!";
		exit();
	}
	
	// if passed then check whether sizes of code, hdi, and appkey == 40
	$code = $_GET['code'];
	$hdi = $_GET['hdi'];
	$appkey = $_GET['appkey'];
	if (strlen(trim($code)) != 40 || strlen(trim($hdi)) != 40 || strlen(trim($appkey)) != 40)
	{
		echo "Usage: Sizes of both code and hdi must be exactly 40 characters!";
		exit();
	}

	// if passed then connect to db
	$mysqli = new mysqli('localhost', 'root', 'project3', 'implauth');
	if ($mysqli->connect_errno)
	{
		echo "Database connection error!";
		exit();
	}

	// if passed then validate code
	$res = $mysqli->query("select count(*) as total from accountstba where code like '$code'");
	$ob = $res->fetch_object();
	$res->close();
	if ($ob->total != 1)
	{
		echo "Error: Code does not exist!";
		$mysqli->close();
		exit();
	}

	// if passed then validate hdvid and appkey
	$res = $mysqli->query("select count(*) as total from hdvid_appkey where hdvid like '$hdi'");
	$ob = $res->fetch_object();
	$res->close();
	$insert_flag = true;
	if ($ob->total == 1)
	{
		// check if appkey is consistent
		$res = $mysqli->query("select count(*) as total from hdvid_appkey where hdvid like '$hdi' and appkey like '$appkey'");
		$ob = $res->fetch_object();
		$res->close();
		if ($ob->total != 1)
		{
			echo "Error: Appkey and device id mismatch. If you reinstalled the app please restore your account on any website associated with your device.";
			$mysqli->close();
			exit;
		}

		$insert_flag = false;
	}

	// if passed then activate account and echo 0
	if ($insert_flag)
	{
		$mysqli->query("insert into hdvid_appkey values ('$hdi', '$appkey')");
	}
	$res = $mysqli->query("select * from accountstba where code like '$code'");
	$ob = $res->fetch_object();
	$res->close();
	$serverid = $ob->serverid;
	$hun = $ob->hun;
	$mysqli->query("insert into accounts values ('$serverid', '$hun', '$hdi', '$appkey')");
	$mysqli->query("delete from accountstba where code like '$code'");
	echo 0;
	
	// close db
	$mysqli->close();

?>
